/**
 * Authen node file
 * type 1 = Account, 2 = Site
 */

var concreateAccount = function(delegate){
	var self = this;
	self.delegate = delegate;
	Mysql.query("SELECT id,email,name FROM Account WHERE id="+Mysql.escape(delegate.getMain().id)+" LIMIT 1", function(error, results){
		if(error) {
			console.log('Mysql error: '+error);
			delegate._error(9999, 'Mysql error');
			return;
		}
		if(results.length == 0) {
			delegate._error(9999, 'Accont not found');
			return;
		}
		delegate._agent = results[0];
		delegate._success(delegate._agent);
	});
};

var concreateSite = function(delegate){
	var self = this;
	self.delegate = delegate;
	Mysql.query("SELECT id,name,ownerId FROM Site JOIN Place ON Site.id=Place.id WHERE Site.id="+Mysql.escape(delegate.getMain().id)+" LIMIT 1", function(error, results){
		if(error) {
			console.log('Mysql error: '+error);
			delegate._error(9999, 'Mysql error');
			return;
		}
		if(results.length == 0) {
			delegate._error(9999, 'Site not found');
			return;
		}
		delegate._agent = results[0];
		delegate._success(delegate._agent);
	});
};

var Authen = function(token, options){
	var self = this;
	self.success = options.success;
	self.error = options.error;
	self._token = token;
	Mysql.query("SELECT * FROM AccessToken JOIN MainID ON MainID.id=AccessToken.agentId WHERE AccessToken.token="+Mysql.escape(self._token)+" LIMIT 1", function(error, results){
		if(error) {
			console.log('Mysql error: '+error);
			self._error(9999, 'Mysql error');
			return;
		}
		if(results.length == 0) {
			self._error(9999, 'Not found token');
			return;
		}
		self._type = results[0].type;
		self._main = results[0];
		if(self._type==1) {
			concreateAccount(self);
		}
		else if(self._type==2) {
			concreateSite(self);
		}
	});
};

Authen.prototype._error = function(code, message){
	if(typeof this.error == 'function') {
		this.error(code, message);
	}
};

Authen.prototype._success = function(data){
	if(typeof this.success == 'function') {
		this.success(data);
	}
};

Authen.prototype.getId = function(){ return this._main.id; };
Authen.prototype.getToken = function(){ return this._token; };
Authen.prototype.getAgent = function(){ return this._agent; };
Authen.prototype.getType = function(){ return this._type; };
Authen.prototype.getMain = function(){ return this._main; };

module.exports = Authen;